﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPNETPerformance.App_BusinessLogic.BasePages;
using ASPNETPerformance.App_BusinessLogic.Cache;

namespace ASPNETPerformance._06_Cache {
    public partial class DataCache : BasePage {
        protected void Page_Load( object sender, EventArgs e ) {
            if ( !this.Page.IsPostBack ) {
                BindData();
            }
        }

        private void BindData() {
            this.GridView1.DataSource = GetProductsByAll();
            this.GridView1.DataBind();
        }

        private DataTable GetProductsByAll() {
            string cacheKey = "ProductsByAll";
            DataTable productsTables = Cache[ cacheKey ] as DataTable;

            if ( productsTables == null ) {
                Trace.Warn( "数据不在Cache中" );

                SqlConnection conn =
                    new SqlConnection( ConfigurationManager.ConnectionStrings[ "NorthwindConnectionString" ].ConnectionString );
                SqlDataAdapter cmd = new SqlDataAdapter( "SELECT Products.ProductName, Categories.CategoryName, Suppliers.CompanyName, Products.QuantityPerUnit, Products.UnitPrice, Products.Discontinued FROM Products INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID ORDER BY Products.ProductName", conn );

                productsTables = new DataTable( "ProductsByAll" );
                cmd.Fill( productsTables );

                Global.DataCache.Add( cacheKey, productsTables );
            }
            else {
                Trace.Warn( "数据在Cache中" );
            }

            return productsTables;
        }
    }
}